package com.etrans.baf.analyse.task.alarm.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import com.etrans.baf.analyse.task.track.service.TouristService;
import com.etrans.baf.analyse.util.DateUtils;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

@Service
public class AnalyseService{
	@Autowired
	private MongoTemplate egovMongoTemplate;//引入配置的mongod模版
	@Autowired
	private TouristService touristService;
	
	static final Logger logger = LoggerFactory.getLogger(AnalyseService.class);
	
	public static Map<Integer,Map<String,Object>> vehicleCache =new HashMap<>();
	/**
	 * 报警分析
	 */
	public void analyseAlarm() {
		DBCollection  db = egovMongoTemplate.getDb().getCollection("gps_info_realtime");
		DBCursor cursor = db.find();
		 if (cursor!=null) {
			 List<DBObject> lob = cursor.toArray();
			 speedAlarm(lob);
			 nightAlarm(lob);
			 tiredAlarm(lob);
		 }
	}
	/**
	 * 疲劳分析
	 */
	public void tiredAlarm(List<DBObject> lob) {
		String tableName = "alarm_analyse_"+DateUtils.getDateTimeString(new Date(),"yyMMdd");
		long startTimeLong = DateUtils.getTimeLong("20:00:00");
		long endTimeLong = DateUtils.getTimeLong("06:00:00");
		long currentTimeLong = DateUtils.getTimeLong(new Date());
		List<DBObject> objList = new ArrayList<DBObject>();
		for (DBObject ob : lob) { 
			 boolean flag = false;
			 Date date = (Date)ob.get("gps_time");
			 if(Math.abs(date.getTime()-new Date().getTime())>1*60*1000){  //相差1分钟以上的数据不分析
				 continue;
			 }
			 int vehicleid = (int)ob.get("vehicle_id");
			 int speed = (int)ob.get("gps_speed");
			 int areaid=1,bizid=1,eid=1;
			 Map<String,Object> temp = vehicleCache.get(vehicleid);
			 if(vehicleCache.get(vehicleid)!=null){
				areaid=vehicleCache.get(vehicleid).get("areaid")==null?1:(int)vehicleCache.get(vehicleid).get("areaid");
				bizid=vehicleCache.get(vehicleid).get("bizid")==null?1:(int)vehicleCache.get(vehicleid).get("bizid");
				eid=vehicleCache.get(vehicleid).get("enterpriseid")==null?1:(int)vehicleCache.get(vehicleid).get("enterpriseid");
			 }else{
				 Map<String,Object> vehicleInfo = new HashMap<>();
				 vehicleInfo.put("id",  (int)ob.get("vehicle_id"));
				 vehicleInfo.put("areaid", areaid);
				 vehicleInfo.put("enterpriseid", eid);
				 vehicleInfo.put("bizid", bizid);
				 vehicleInfo.put("restTime", 0d);    //休息时间
				 vehicleInfo.put("runTime", 0d);     //行驶时间
				 vehicleInfo.put("lastTime", date);
				 vehicleCache.put((int)ob.get("vehicle_id"), vehicleInfo);
				 temp = vehicleCache.get(vehicleid);
			 }
			 
			 //速度大于0 休息时间置 0，速度等于0 累加休息时间
			 double restTime = temp.get("restTime")==null?0d:Double.valueOf(temp.get("restTime").toString());
			 double runTime = temp.get("runTime")==null?0d:Double.valueOf(temp.get("runTime").toString());
			 Date lastTime = (Date)temp.get("lastTime");
			 if( (date.getTime()-lastTime.getTime())*0.001>20*60){
				 temp.put("runTime",0d);
				 temp.put("restTime", 0);
			 }else{
				 if(speed>0){
					 temp.put("restTime", 0);
					 restTime=0;
					 temp.put("runTime", (date.getTime()-lastTime.getTime())*0.001+runTime);
					 runTime=(double) ((date.getTime()-lastTime.getTime())*0.001+runTime);
				 }else{
					 temp.put("restTime", restTime+(date.getTime()-lastTime.getTime())*0.001);
					 restTime = (double) (restTime+(date.getTime()-lastTime.getTime())*0.001);
					 temp.put("runTime", (date.getTime()-lastTime.getTime())*0.001+runTime);
					 runTime = (double) ((date.getTime()-lastTime.getTime())*0.001+runTime);
				 }
			 }
			 temp.put("lastTime", date);
			 if(currentTimeLong>endTimeLong&&currentTimeLong<startTimeLong){  
				// 日间连续行驶4小时,且没有休息20分钟
				 if(runTime>4*60*60&&restTime<20*60){
					 flag=true;
				 }
				 if(restTime>=20*60){  //休息20分钟 行驶时间置0
					 temp.put("runTime",0d);	
				 }
			 }else{
				// 夜间连续行驶2小时,且没有休息20分钟
				 if(runTime>2*60*60&&restTime<20*60){
					 flag=true;
				 }
				 if(restTime>=20*60){     //休息20分钟 行驶时间置0
					 temp.put("runTime",0d);	
				 }
			 }
//			 logger.info("车辆 ："+ob.get("vehicle_no")+"rumTime :"+runTime+"--"+" restTime: "+restTime +"--lastTime:"+lastTime+"--速度："+speed);
			 if(flag){
				 DBObject entity = new BasicDBObject();
				 entity.put("alarm_time",(Date)ob.get("gps_time"));
				 entity.put("area_id",areaid);
				 entity.put("biz_id", bizid);
				 entity.put("coordinates", ob.get("coordinates"));
				 entity.put("enterprise_id", eid);
				 entity.put("gnsscenter_id", (int)ob.get("gnsscenter_id"));
				 entity.put("platform_id", (int)ob.get("platform_id"));
				 entity.put("vehicle_color", (int)ob.get("vehicle_color"));
				 entity.put("vehicle_id", (int)ob.get("vehicle_id"));
				 entity.put("vehicle_no", ob.get("vehicle_no"));
				 entity.put("alarm_type",2);
				 entity.put("alarm_name", "疲劳驾驶报警");
		    	 objList.add(entity);
			 }
	    }
		egovMongoTemplate.insert(objList, tableName);
		
	}
	/**
	 * 超速
	 */
	public void speedAlarm(List<DBObject> lob) {
		// 检测速度是否大于等于設定速度
		String tableName = "alarm_analyse_"+DateUtils.getDateTimeString(new Date(),"yyMMdd");
		long startTimeLong = DateUtils.getTimeLong("20:00:00");
		long endTimeLong = DateUtils.getTimeLong("06:00:00");
		long currentTimeLong = DateUtils.getTimeLong(new Date());
		int speedO = 64,speedT = 80,speedF = 96;
		if(currentTimeLong>endTimeLong&&currentTimeLong<startTimeLong){  // 6点到20点间算 白天
			speedO = 80;speedT = 100;speedF =120;
		}
		List<DBObject> objList = new ArrayList<DBObject>();
		for (DBObject ob : lob) { 
			 Date date = (Date)ob.get("gps_time");
			 int speed = (int)ob.get("gps_speed");
			 if(Math.abs(date.getTime()-new Date().getTime())>1*60*1000){
				 continue;
			 }
			 int vehicleid = (int)ob.get("vehicle_id");
			 int areaid=1,bizid=1,kindid=40,eid=1;
			 if(vehicleCache.get(vehicleid)!=null){
				 areaid=vehicleCache.get(vehicleid).get("areaid")==null?1:(int)vehicleCache.get(vehicleid).get("areaid");
				 kindid=vehicleCache.get(vehicleid).get("kindid")==null?1:(int)vehicleCache.get(vehicleid).get("kindid");
				 bizid=vehicleCache.get(vehicleid).get("bizid")==null?1:(int)vehicleCache.get(vehicleid).get("bizid");
				 eid=vehicleCache.get(vehicleid).get("enterpriseid")==null?1:(int)vehicleCache.get(vehicleid).get("enterpriseid");
			 }
			 // 小型载客汽车最高车速不得超过120km/h；大中型载客汽车最高车速不得超过100km/h；危险货物运输车辆在高速公路上最高车速不得超过80km/h
			 // 且车辆夜间行驶速度不得超过日间限速80%
			
			 if((kindid==40&&speed>speedO)||(kindid==11&&speed>speedT)||(kindid==12&&speed>speedT)||(speed>speedF)){
				 DBObject entity = new BasicDBObject();
				 entity.put("alarm_time",(Date)ob.get("gps_time"));
				 entity.put("area_id",areaid);
				 entity.put("biz_id", bizid);
				 entity.put("coordinates", ob.get("coordinates"));
				 entity.put("enterprise_id", eid);
				 entity.put("gnsscenter_id", (int)ob.get("gnsscenter_id"));
				 entity.put("platform_id", (int)ob.get("platform_id"));
				 entity.put("vehicle_color", (int)ob.get("vehicle_color"));
				 entity.put("vehicle_id",  (int)ob.get("vehicle_id"));
				 entity.put("vehicle_no", ob.get("vehicle_no"));
				 entity.put("alarm_type",1);
				 entity.put("alarm_name", "超速报警");
		    	 objList.add(entity);
			 }
	    }
//		logger.info("超速报警 入库数据长度："+objList.size());
		egovMongoTemplate.insert(objList, tableName);
	}
	/**
	 * 车辆禁行
	 */
	public void nightAlarm(List<DBObject> lob) {
		// 检测速度是否大于等于設定速度
		String tableName = "alarm_analyse_"+DateUtils.getDateTimeString(new Date(),"yyMMdd");
		long startTimeLong = DateUtils.getTimeLong("02:00:00");
		long endTimeLong = DateUtils.getTimeLong("05:00:00");
		List<DBObject> objList = new ArrayList<DBObject>();
		for(DBObject ob : lob){
			Date date = (Date)ob.get("gps_time");
			int speed = (int)ob.get("gps_speed");
			if(Math.abs(date.getTime()-new Date().getTime())>1*60*1000){
				 continue;
			}
			int vehicleid = (int)ob.get("vehicle_id");
			int areaid=1,bizid=1,eid=1;
			if(vehicleCache.get(vehicleid)!=null){
				areaid=vehicleCache.get(vehicleid).get("areaid")==null?1:(int)vehicleCache.get(vehicleid).get("areaid");
				bizid=vehicleCache.get(vehicleid).get("bizid")==null?1:(int)vehicleCache.get(vehicleid).get("bizid");
				eid=vehicleCache.get(vehicleid).get("enterpriseid")==null?1:(int)vehicleCache.get(vehicleid).get("enterpriseid");
			}
			long currentTimeLong = DateUtils.getTimeLong((Date)ob.get("gps_time"));
			// 车辆在凌晨2-5点是须休息、禁止运行（速度大于0km/h为运行）的，否则记录为车辆凌晨2-5点禁行违规
			if(currentTimeLong<endTimeLong&&currentTimeLong>startTimeLong&&speed>0){
				DBObject entity = new BasicDBObject();
				entity.put("alarm_time",(Date)ob.get("gps_time"));
				entity.put("area_id",areaid);
				entity.put("biz_id", bizid);
				entity.put("coordinates", ob.get("coordinates"));
				entity.put("enterprise_id", eid);
				entity.put("gnsscenter_id", (int)ob.get("gnsscenter_id"));
				entity.put("platform_id", (int)ob.get("platform_id"));
				entity.put("vehicle_color", (int)ob.get("vehicle_color"));
				entity.put("vehicle_id", (int)ob.get("vehicle_id"));
				entity.put("vehicle_no", ob.get("vehicle_no"));
				entity.put("alarm_type",14);
				entity.put("alarm_name", "2-5点禁行报警");
				objList.add(entity);
			}
			
		}
//		logger.info("凌晨2-5点 入库数据长度："+objList.size());
		egovMongoTemplate.insert(objList, tableName);
	}
	
	@SuppressWarnings("unchecked")
	public void initVehicleInfo() {
		List<Map<String,Object>> result =touristService.getVehicleInfo();
		for(int i=0;i<result.size();i++){
			if(vehicleCache.containsKey(Integer.valueOf(result.get(i).get("id").toString()))){
				Map<String,Object> map = vehicleCache.get(Integer.valueOf(result.get(i).get("id").toString()));
				map.put("areaid", result.get(i).get("areaid")==null?1:(int)result.get(i).get("areaid"));
				map.put("kindid", result.get(i).get("kindid")==null?999:(int)result.get(i).get("kindid"));
				map.put("bizid", result.get(i).get("bizid")==null?1:(int)result.get(i).get("bizid"));
				map.put("enterpriseid", result.get(i).get("enterpriseid")==null?1:Integer.valueOf(result.get(i).get("enterpriseid").toString()));
			}else{
				Map<String,Object> map = new HashMap<>();
				map.put("id", Integer.valueOf(result.get(i).get("id").toString()));
				map.put("areaid", result.get(i).get("areaid")==null?1:(int)result.get(i).get("areaid"));
				map.put("kindid", result.get(i).get("kindid")==null?999:(int)result.get(i).get("kindid"));
				map.put("bizid", result.get(i).get("bizid")==null?1:(int)result.get(i).get("bizid"));
				map.put("restTime", 0d);   //休息时间
				map.put("rumTime", 0d);    //行驶时间 
				map.put("enterpriseid", result.get(i).get("enterpriseid")==null?1:Integer.valueOf(result.get(i).get("enterpriseid").toString()));
				map.put("lastTime", new Date());
				vehicleCache.put(Integer.valueOf(result.get(i).get("id").toString()), map);
			}
		}
	}

}
